﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Web;
using System.IO;
using System.Diagnostics;
using Ionic.Zip;
using NLog;

namespace CachingWebClient
{
   public static class CacheManager
   {
      private static Logger Log = LogManager.GetCurrentClassLogger();

      private static Dictionary<string, object> mCache;

      static CacheManager()
      {
         mCache = new Dictionary<string, object>();
      }

      private static string GetCachedWebString(string url)
      {
         if (mCache.ContainsKey(url))
            return (string)mCache[url];
         else
            return null;
      }

      private static ZipFile GetCachedWebZip(string url)
      {
         if (mCache.ContainsKey(url))
            return (ZipFile)mCache[url];
         else
            return null;
      }

      public static string GetWebString(string url)
      {
         string cache = GetCachedWebString(url);

         if (cache == null)
         {
            Log.Trace("CacheManager.GetWebString:  Retrieving: {0}...", url);

            WebClient wc = new WebClient();
            cache = wc.DownloadString(url);
            mCache.Add(url, cache);
         }
         else
            Log.Trace("CacheManager.GetWebString:  Retrieving: {0} [CACHED]", url);

         return cache;
      }

      public static ZipFile GetWebZip(string url)
      {
         ZipFile cache = GetCachedWebZip(url);

         if (cache == null)
         {
            Log.Trace("CacheManager.GetWebZip:  Retrieving: {0}...", url);

            WebClient wc = new WebClient();
            MemoryStream ms = new MemoryStream(wc.DownloadData(url));

            cache = ZipFile.Read(ms);
            mCache.Add(url, cache);
         }
         else
            Log.Trace("CacheManager.GetWebZip:  Retrieving: {0} [CACHED]", url);

         return cache;
      }
   }
}
